<script lang="ts" setup>
import pageVue from "/src/lib/lay/page.vue";
import control from "/src/lib/action/control.vue";
import { ref, reactive } from "@vue/runtime-core";
import { $ } from "../../../../lib/request";
import { modal } from "vxe-table";
import { IDCardNumber,CarId} from '/src/lib/encrypt/editRules.ts'

const priceList={} as any;
const Pagechildren = [{ name: "top" }];
let Data = ref([] as Array<any>);

// 反正以后要大改，就先不写到状态里了 初始的数值
const itemData = ref({
    精品级配砂: 0,
    精品瓜子片: 0,
    精品二分石: 0,
    精品三分石: 0,
    石粉: 0,
    瓜子片: 0,
    三分石: 0,
    机制砂: 0,
    泥饼: 0,
    粉末: 0,
  } as any),
  isEdit = ref(false);

// 删除对象空属性
const removeEmpty = (obj: any) => {
  Object.keys(obj).forEach((key) => {
    !obj[key] && obj[key] != 0 && delete obj[key];
  });
  return obj;
};

// 初始化空对象
const initEmpty = (obj: object, init: number) => {
  Object.keys(obj).forEach((key) => {
    obj[key] !== init && !obj[key] && (obj[key] = init);
  });
  return obj;
};
//确认修改
const setItem = () => {
  $.get("oa/saas/product/ylxg.do", {
    params: { ...itemData.value },
  }).then((respose)=>{
    // console.log(respose);
    isEdit.value = false;
     modal.message({ content:respose.data.message, status: "success" });
     
  });

};

//图表一配置项
const gridOptions = reactive({
  border: true,
  resizable: false,
  height: 330,
  rowId: "id",
  checkboxConfig: {
    reserve: true,
  },
  pagerConfig: {
    pageSize: 10,
  },
  editConfig: { trigger: "click", mode: "row", enabled: true },
 editRules: {
    "nickname":CarId,
    "IDCardNumber": IDCardNumber,
  },
  columns: [
    {
      type: "checkbox",
      width: 50,
    },
    { field: "khmc", title: "客户名称" },
    { field: "contractAmount", title: "合同额" },
    {
      field: "advancePay",
      title: "预付款",
      showOverflow: true,
    },
    {
      field: "createTime",
      title: "付款时间",
      showOverflow: true,
    },
    {
      field: "advancePayBalance",
      title: "派单前余额",
      showOverflow: true,
    },
    {
      field: "pdqye",
      title: "派单后余额",
      showOverflow: true,
    },
  ],
  proxyConfig: {
    seq: true, // 启用动态序号代理（分页之后索引自动计算为当前页的起始序号）
    props: {
      result: "result",
      total: "page.total",
    },
    ajax: {
      // 接收 Promise
      query: ({
        page: { currentPage, pageSize },
      }: {
        page: {
          currentPage: number;
          pageSize: number;
        };
      }) => {
        return new Promise((resolve) => {
          const list = [] as any[];
          $.get("oa/saas/product/khxx.do", { params: {} }).then((tableData) => {
            tableData.data?.data?.khxx?.forEach(
              ({
                id,
                khmc,
                contractAmount,
                advancePay,
                createTime,
                advancePayBalance,
                pdqye,...price
              }: any) => {
                priceList[khmc]=price
                list.push({
                  khmc,
                  contractAmount,
                  advancePay,
                  createTime,
                  advancePayBalance,
                  pdqye,
                  id
                });
              }
            );
            resolve({
              page: {
                total: list.length,
              },
              result: list.slice(
                (currentPage - 1) * pageSize,
                currentPage * pageSize
              ),
            });
          });
        });
      },
    },
  },
});
//图表二配置项
const gridOptions2 = reactive({
  border: true,
  resizable: false,
  height: 530,
  rowId: "id",
  checkboxConfig: {
    reserve: true,
  },
  pagerConfig: {
    pageSize: 10,
  },
  editConfig: { trigger: "click", mode: "row", enabled: true },

  columns: [
    {
      type: "checkbox",
      width: 50,
    },
    { field: "khmc", title: "客户名称", editRender: { name: "$input" } },
    {
      field: "精品级配砂",
      title: "精品级配砂（吨）",
      editRender: { name: "$input" },
    },
    {
      field: "精品瓜子片",
      title: "精品瓜子片（吨）",
      editRender: { name: "$input" },
    },
    {
      field: "精品二分石",
      title: "精品二分石（吨）",
      editRender: { name: "$input" },
    },
    {
      field: "精品三分石",
      title: "精品三分石（吨）",
      editRender: { name: "$input" },
    },
    { field: "机制砂", title: "机制砂（吨）", editRender: { name: "$input" } },
    { field: "石粉", title: "石粉（吨）", editRender: { name: "$input" } },
    { field: "瓜子片", title: "瓜子片（吨）", editRender: { name: "$input" } },
    { field: "三分石", title: "三分石（吨）", editRender: { name: "$input" } },
    { field: "粉末", title: "粉末（吨）", editRender: { name: "$input" } },
    { field: "泥饼", title: "泥饼（吨）", editRender: { name: "$input" } },
  ],
  proxyConfig: {
    seq: true, // 启用动态序号代理（分页之后索引自动计算为当前页的起始序号）
    props: {
      result: "result",
      total: "page.total",
    },
    ajax: {
      // 接收 Promise
      query: ({
        page: { currentPage, pageSize },
      }: {
        page: {
          currentPage: number;
          pageSize: number;
        };
      }) => {
        return new Promise((resolve) => {
          setTimeout(() => {
            const list = [] as any[];
            resolve({
              page: {
                total: list.length,
              },
              result: list.slice(
                (currentPage - 1) * pageSize,
                currentPage * pageSize
              ),
            });
          }, 100);
        });
      },
    },
  },
});
//图表三派单反馈配置项
const gridOptions3 = reactive({
  border: true,
  resizable: false,
  height: 330,
  rowId: "id",
  checkboxConfig: {
    reserve: true,
  },
  pagerConfig: {
    pageSize: 10,
  },
  editConfig: { trigger: "click", mode: "row", enabled: false },
 editRules: {
    "nickname":CarId,
    "IDCardNumber": IDCardNumber,
  },
  columns: [
    {
      type: "checkbox",
      width: 50,
    },
    { field: "customerName", title: "客户名称" },
    { field: "createTime", title: "派单时间" },
    { field: "carCard", title: "车牌号" },
    {
      field: "productName",
      title: "物料名称",
      showOverflow: true,
    },
    {
      field: "truck",
      title: "数量(吨)",
      showOverflow: true,
    },
    {
      field: "driverName",
      title: "司机姓名",
      showOverflow: true,
    },
    {
      field: "phone",
      title: "联系电话",
      showOverflow: true,
    },
    {
      field: "idCard",
      title: "身份证号",
      showOverflow: true,
    },
  ],
  proxyConfig: {
    seq: true, // 启用动态序号代理（分页之后索引自动计算为当前页的起始序号）
    props: {
      result: "result",
      total: "page.total",
    },
    ajax: {
      // 接收 Promise
      query: ({
        page: { currentPage, pageSize },
      }: {
        page: {
          currentPage: number;
          pageSize: number;
        };
      }) => {
        return new Promise((resolve) => {
          const list = [] as any[];
          $.get("oa/saas/core/productcar/pdfk.do", { params: {} }).then((tableData) => {
            console.log('3',tableData);
            
            tableData.data?.data?.list?.forEach(
              ({
               ...item
              }: any) => {
                list.push({
               ...item
                });
              }
            );
            resolve({
              page: {
                total: list.length,
              },
              result: list.slice(
                (currentPage - 1) * pageSize,
                currentPage * pageSize
              ),
            });
            // Data.value=tableData.data.data.productList
          });
        });
      },
    },
  },
});
const yTable = ref({} as any);
const xTable = ref({} as any);
const getSelectionEvent = () => {
  const $table = xTable.value;
  const selectRecords = $table.getCheckboxRecords();
  // modal.alert(`选中：${selectRecords.length}`)
  // insertEvent()
  const $table2 = yTable.value;
  selectRecords.forEach(async (item: any) => {
    const { row: newRow } = await $table2.insertAt({ khmc: item.khmc,id: item.id }, 0);
    await $table2.setActiveCell(newRow, "khmc");
  });
};
const getItemPrice=({khmc,...item}:any)=>{
  const thisPrice=priceList[khmc];
  console.log('價格表',priceList,thisPrice);
  
  let total=0;
  const priceChar={
   
    "精品瓜子片":'jpgzpdj',
    "精品级配砂":'jpjpsdj',
    "精品二分石":'jpefsdj',
    "精品三分石":'jpsfsdj',
    "机制砂":'jzsdj',
    "石粉":'sfdj',
    "瓜子片":'gzpdj',
    "三分石":'sfsdj',
    "粉末":'fmdj',
    "泥饼":'nbdj',
  }
  Object.keys(item).forEach((key)=>{
// console.log();

    total+=thisPrice[priceChar[key]]*item[key]||0
  })
  
  return total
}
const handlePaidan = () => {

const $table = yTable.value;

    const selectRecords = $table.getCheckboxRecords();
    const addList=[] as any[]
    selectRecords.forEach(({...item}:any) => {
      addList.push(initEmpty({
        ...item,
        total:getItemPrice(item)
      },0))
    });

console.log('长期客户派单',JSON.stringify(addList).replace(/^\[+|\]+$/g, ''));

  $.get("oa/saas/product/addProduct.do", { params: {
    addList:JSON.stringify(addList).replace(/^\[+|\]+$/g, '')

  } }).then((respose) => {
    name() 
  modal.message({ content: respose.data.message, status: "success" });
      // modal.message({'respose.data.message'});
      $table.removeCheckboxRow()

  
  });
};
name()
function name() {
//给contol组件赋值
 $.get("oa/saas/product/ylyc.do", {params:{},}).then((data)=>{
    var arr =data.data.data.ylyc
    const mockData = {
    精品级配砂: 0,
    精品瓜子片: 0,
    精品二分石: 0,
    精品三分石: 0,
    石粉: 0,
    瓜子片: 0,
    三分石: 0,
    机制砂: 0,
    泥饼: 0,
    粉末: 0,
  };
arr.forEach( ({productForeast ,productName}: any) => {
     mockData[productName]=productForeast  
    });
    // console.log(mockData);
  itemData.value = initEmpty({ ...mockData }, 0);
 });

 }
const fk=ref(false)
</script>

<template lang="pug">
pageVue(:children='Pagechildren')
  template(v-slot:top)
    .hjk
      .topp 长期客户派单
      control(:itemData="itemData" :isEdit="isEdit")
        template(v-slot:title)
          .title 余量预测
      div(style="display: flex;justify-content: center")
        button.bott(@click="isEdit = !isEdit" style="margin-right: 67px;") {{ isEdit ? '取消修改' : '修改余量' }}
        button.bott(v-if="isEdit" @click="setItem") 确认修改
      vxe-grid(v-bind="gridOptions"   ref="xTable" highlight-hover-row  )
      button.bott(style="text-align: center;"  @click="getSelectionEvent") 一键派单
      vxe-grid(v-bind="gridOptions2"   ref="yTable"  highlight-hover-row  )
      .bot
        button.bott(style="margin-right: 68px;"   @click="yTable.removeCheckboxRow()" ) 删除
        button.bott(style="margin-right: 68px;"  @click="handlePaidan" ) 确认派单
        button.bott(style="margin-right: 68px;"  @click="fk=!fk") 派车反馈
        vxe-modal(v-model="fk" title="处理信息" width="1300" height="500" show-zoom resize)
          template(#default)
            vxe-grid(v-bind="gridOptions3"   ref="xTable" highlight-hover-row  )
</template>
<style lang="scss" scoped>
.hjk {
  display: grid;
  gap: 20px;
  padding: 48px;
}
.topp {
  font-size: 20px;
  font-weight: bold;
  line-height: 20px;
  color: #5d5d5d;
}
.headerr {
  width: 86%;
  margin: 20px auto;
  font-size: 18px;
  font-family: Source Han Sans CN;
  line-height: 36px;
  color: #000000;
  background: #f0faf2;
  border-radius: 10px;
  padding: 20px;
  .text {
    margin-left: 40px;
  }
}
.mid {
  font-size: 18px;
  color: #5d5d5d;
  font-weight: bold;
}
.bot {
  // display: flex;
  text-align: center;
  margin-bottom: -20px;
}
.bott {
  cursor: pointer;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  width: 94px;
  height: 34px;
  background: #f0faf2;
  box-shadow: 1px 1px 4px rgba(0, 0, 0, 0.16);
  border-radius: 10px;
  font-size: 18px;
  line-height: 34px;
  color: #5d5d5d;
  border: none;
}
</style>
